package yyee.llee.mmee.base_api_net


import android.util.Log
import yyee.llee.mmee.pl190.host668.StrongContext
import okhttp3.*
import okio.Buffer
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
import java.util.*


/**
 * 加密操作
 */
class RequestInterceptor : Interceptor {

    private val TAG: String = "KY_HTTP===="
    private var isOpenLog = true

    private val AESKEY = "738a17961e8c34aefb11837713a875fa"
    private val PARAMSKEY = "4fdbb6092097773d"


    override fun intercept(chain: Interceptor.Chain): Response {
        isOpenLog = true
        var request = chain.request()
        var charset = Charset.forName("UTF-8")
        //不是Get和Delete请求时，则请求数据在请求体中
        val requestBody = request.body()
        /*判断请求体是否为空  不为空则执行以下操作*/
        if (requestBody != null) {
            val contentType = requestBody.contentType()
            logI( "HTTP contentType========"+contentType)
            /*获取请求的数据*/
            try {
                val requestData = getRequestInfo(request)
                /*构建新的requestBuilder*/
                val newRequestBuilder = request.newBuilder()

                newRequestBuilder.addHeader("X-ABBR", "android")
                newRequestBuilder.addHeader("X-APPCODE", "mqhz")
                newRequestBuilder.addHeader("X-APPID", "1035")
                newRequestBuilder.addHeader("X-NONCESTR", yyee.llee.mmee.base_api_net.utils.MD5Util.getMD5code(UUID.randomUUID().toString()))//随机字符串，md5加密后，截取前八位字符(每次请求生成一次)
                if (yyee.llee.mmee.common.global.Env.isDebug) {
                    newRequestBuilder.addHeader("X-RUN", "debug")
                } else {
                    newRequestBuilder.addHeader("X-RUN", "release")
                }
                //时间差值
                val secondTime = System.currentTimeMillis() / 1000
                newRequestBuilder.addHeader( "X-TIMESTAMP", "" + (secondTime + yyee.llee.mmee.pl190.host668.SharedPreUtils.getInstance().getInt(
                    yyee.llee.mmee.pl190.host668.SharedPreUtils.TIME_DIFF,0)))//秒级时间戳
                newRequestBuilder.addHeader("X-TRICE", "" + UUID.randomUUID())//随机字符串，uuid（每次请求生成一次）
                newRequestBuilder.addHeader("X-VERSION", yyee.llee.mmee.common.global.Env.VERSION)
                request = newRequestBuilder.build()
                val url:String = request.url().toString()
                logI( "request.url==" + url)
                val encrypt = yyee.llee.mmee.base_api_net.utils.AesUtil.encrypt(requestData)
                logI(  "request.params==" + requestData)
//                logI(  "request.params加密后==" + encrypt)
                val sb = StringBuilder()
                val headers = request.headers()
                val headerCount = headers.size()
                for(i in 0 until headerCount ) {
                    sb.append( headers.name(i)+ "=" + headers.value(i) + "&")
                }
                sb.replace(sb.length - 1, sb.length, "")
                val str1 = sb.toString().lowercase() //拼接后转换为小写
//                logI(  "接口Hader拼接后小写==" + str1)
                val str2 =  PARAMSKEY
                val str3 = encrypt;
                val str4 = str1+str2+str3
                val mD5code = yyee.llee.mmee.base_api_net.utils.MD5Util.getMD5code(str4)
//                logI( "MD5混淆后===="+mD5code)
                val substring = mD5code.substring(5, 15)
//                logI( "MD5混淆后截取5---15===="+substring)
                newRequestBuilder.addHeader("X-SIGN", substring)//签名（签名算法生成）
                newRequestBuilder.addHeader("User-Agent", yyee.llee.mmee.pl190.host668.DeviceUtils.getWebUA())
                newRequestBuilder.addHeader(  "X-DEVICEID",  yyee.llee.mmee.pl190.host668.DeviceUtils.getAndroidId(
                    StrongContext.getApplication()))//设备android id
                newRequestBuilder.addHeader( "X-OAID",
                    yyee.llee.mmee.pl190.host668.DeviceUtils.getOaId())//设备android oaid
//                if (!TextUtils.isEmpty(DeviceUtils.getPhoneImei(CContext.getApplication()))){
//                    newRequestBuilder.addHeader( "X-IMEI",DeviceUtils.getPhoneImei(CContext.getApplication()))//设备android imei
//                }
                /*构建新的请求体*/
                val newRequestBody = RequestBody.create(contentType, encrypt)
                newRequestBuilder.post(newRequestBody)
                request = newRequestBuilder.build()
                logI(  "request.headers==" + request.headers().toString())
            } catch (e: Exception) {
                Log.e(TAG,"Exception===="+e)
                return chain.proceed(request)
            }
        }

        var response = chain.proceed(request)
        val responseHeader = response.headers()
        //记录时间和server的差值
        responseHeader["SERVER-TIMESTAMP"]?.let {
            val serverTime = it.toLong()
            val clientTime = System.currentTimeMillis() / 1000
            val result = (serverTime - clientTime).toInt()
            yyee.llee.mmee.pl190.host668.SharedPreUtils.getInstance().putInt(
                yyee.llee.mmee.pl190.host668.SharedPreUtils.TIME_DIFF,result)

        }
        val responseBody = response.body()
        if (responseBody != null) {
            /*开始解密*/
            try {
                val source = responseBody.source()
                source.request(java.lang.Long.MAX_VALUE)
                val buffer = source.buffer()
                var charset = Charset.forName("UTF-8")
                val contentType = responseBody.contentType()
                if (contentType != null) {
                    charset = contentType.charset(charset)
                }
                val bodyString = buffer.clone().readString(charset)
                val jsonObject = JSONObject(bodyString)
                val decryptJsonData = jsonObject.getString("data")
                val decryptJsonMsg = jsonObject.getString("msg")
                val decryptJsonCode = jsonObject.getInt("code")
                var decrypt = yyee.llee.mmee.base_api_net.utils.AesUtil.decrypt(decryptJsonData,AESKEY)
                val newJson = JSONObject()
                if(decrypt.isNullOrEmpty() || "null" == decrypt){
                    decrypt = "{}"
                }
                val newDataJson = JSONObject(decrypt)

                newJson.put("data",newDataJson)
                newJson.put("msg",decryptJsonMsg)
                newJson.put("code",decryptJsonCode)
                logI("bodyString  解密后重新生成decrypt==${request.url()} ==== $newJson")

                if (request.url().toString().endsWith("ad/report")){
                    //测试打印日志
                    Log.i("AD_Report","CODE=="+decryptJsonCode+"===MSG==="+decryptJsonMsg+"\n====DATA====="+newJson.toString())
                }

                val newResponseBody = ResponseBody.create(contentType, newJson.toString())
                response = response.newBuilder().body(newResponseBody).build()


            } catch (e: Exception) {
                /*异常说明解密失败 信息被篡改 直接返回即可 */
                bi.GL.ld(TAG, "解密异常====》$e")
                return response
            }

            return response
        } else {
            bi.GL.ld(TAG, "响应体为空")
        }

        return chain.proceed(request)
    }

    private fun logI(info:String){

            bi.GL.ld(TAG,""+info)

    }

    /**
     * 打印请求消息
     *
     * @param request 请求的对象
     */
    private fun getRequestInfo(request: Request?): String? {
        var str = ""
        if (request == null) {
            return str
        }
        val requestBody = request.body() ?: return str
        try {
            val bufferedSink = Buffer()
            requestBody.writeTo(bufferedSink)
            val charset = Charset.forName("utf-8")
            str = bufferedSink.readString(charset)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return str
    }

}